from collections import OrderedDict

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as mtick
from matplotlib.font_manager import FontProperties
import pandas as pd

df = pd.read_csv('./score_0418.txt', sep='\t')

df = df[['y', 'newprob']]
# print(df)

cut_point = [0.25, 0.3, 0.35, 0.4, 0.5, 0.6, 0.7]


def test(df, cut_point):
    score_list = []
    info = OrderedDict()
    cut_point.append(1)
    for point in cut_point:
        info_dict = OrderedDict()
        if cut_point.index(point) == 0:
            gruop = [0, point]
        else:
            gruop = [cut_point[cut_point.index(point) - 1], point]
        info_dict['cnt'] = str(gruop)
        info_dict['bad_cnt'] = df[(df['newprob'] > gruop[0]) & (df['newprob'] <= gruop[1])][df['y'] == 1].count()['y']
        info_dict['all_cnt'] = df[(df['newprob'] > gruop[0]) & (df['newprob'] <= gruop[1])].count()['y']
        # info_dict['odu_or'] = format(info_dict['bad_cnt'] / info_dict['all_cnt'], '.2%')
        info_dict['odu_or'] = info_dict['bad_cnt'] / info_dict['all_cnt'] * 100
        # info_dict['peo_or'] = format((info_dict['all_cnt'] / df.shape[0]), '.2%')
        info_dict['peo_or'] = info_dict['all_cnt'] / df.shape[0] * 100
        score_list.append(info_dict)
    info['cnt'] = 'sum'
    info['bad_cnt'] = df[df['y'] == 1].count()[0]
    info['all_cnt'] = df.shape[0]
    info['odu_or'] = info['bad_cnt'] / info['all_cnt'] * 100
    score_list.append(info)
    cut_point.pop()
    return pd.DataFrame(score_list)


ret_df = test(df, cut_point)

# font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)
# b = [23.4, 25.6, 33.3, 37.3, 43.2, 48.5, 48.9, 53.6, 65.3, 61.4, 85.5]  # 逾期率数据
# a = [8.8, 10.0, 13.0, 13.2, 13.8, 13.2, 8.9, 7.3, 4.8, 2.9, 4.0]  # 人数占比
# l = [i for i in range(11)]

b = list(ret_df['odu_or'][:-1])  # 逾期率
a = list(ret_df['peo_or'][:-1])  # 人数占比
l = [i for i in range(len(a))]
# 柱图显示人数占比，折线代表逾期率

plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签

fmt = '%.2f%%'
yticks = mtick.FormatStrFormatter(fmt)  # 设置百分比形式的坐标轴
lx = l

# 折线图
fig = plt.figure(figsize=(13, 8))
ax1 = fig.add_subplot(111)
ax1.plot(l, b, 'or-', label='逾期率')
ax1.yaxis.set_major_formatter(yticks)

for i, (_x, _y) in enumerate(zip(l, b)):
    plt.text(_x, _y, '%.2f%%' % round(b[i]), color='black', fontsize=10, )  # 将数值显示在图形上
ax1.legend(loc=1)
ax1.set_ylim([-20, 30])
ax1.set_ylabel('逾期率')
plt.legend(prop={'family': 'SimHei', 'size': 8})  # 设置中文

# 柱状图
ax2 = ax1.twinx()  # this is the important function
ax2.yaxis.set_major_formatter(yticks)
plt.bar(l, a, alpha=0.3, color='blue', label='人数占比')
ax2.legend(loc=2)
ax1.set_ylim([0, max(b) * 1.2])  # 设置y轴取值范围
ax2.set_ylabel('人数占比')
plt.legend(prop={'family': 'SimHei', 'size': 8}, loc="upper left")
plt.xticks(l, lx)
plt.show()
